package me.yangteng.zhihudaily.util;

import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by MorenYang on 2017/12/18.
 */

public class HttpLoader extends AsyncTask<String, Void, String> {
  private static final String TAG = "HttpLoader";
  private HttpLoaderListener httpLoaderListener;

  @Override
  protected String doInBackground(String... strings) {
    String urlString = strings[0];
    try {
      Log.d(TAG, "HttpLoader " + urlString);
      OkHttpClient okHttpClient = new OkHttpClient();
      Request request = new Request.Builder()
        .url(urlString)
        .build();
      Response response = okHttpClient.newCall(request).execute();
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
      return response.body().string();
    } catch (Exception e) {
      e.printStackTrace();
      Log.e(TAG, e.toString());
      return null;
    }
  }

  public interface HttpLoaderListener {
    void onGetHttpString(String string);

    void onError(Exception e);
  }

  public void setHttpLoaderListener(HttpLoaderListener listener) {
    this.httpLoaderListener = listener;
  }

  @Override
  protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
      this.httpLoaderListener.onGetHttpString(s);
    } catch (Exception e) {
      Log.d(TAG, e.toString());
      this.httpLoaderListener.onError(e);
    }
  }

  public static void onErrorHandler(View view) {
    Snackbar.make(view, "网络错误", Snackbar.LENGTH_LONG)
      .setAction("Action", null).show();
  }
}
